package com.hsq.commons.util;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtil {
	public String getTable(String filename,String table_name) {
		SAXReader saxReader = new SAXReader();
		StringBuffer sb_temp = new StringBuffer("");
		StringBuffer sb = new StringBuffer("");
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();
			for (Iterator iter = root.elementIterator(); iter.hasNext();) {
				Element element = (Element) iter.next();
				//System.out.println(element.getName());
				if (element.getName().equals(table_name)) {
					for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
						Element element1 = (Element) iterInner.next();
						sb_temp.append("'");
						for (Iterator iterInner1 = element1.elementIterator(); iterInner1.hasNext();) {
							Element elementInner = (Element) iterInner1.next();
							sb_temp.append(elementInner.getText());
							sb_temp.append("','");
						}
						sb.append(sb_temp.substring(0,sb_temp.length() -2));
						sb.append(" ");
						sb_temp.delete(0, sb_temp.length());
					}
				}
			}
			//System.out.println(sb.toString());
			return sb.toString();
		} catch (DocumentException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	public static String getElementValue(String filename,String key) {
		SAXReader saxReader = new SAXReader();
		StringBuffer sb = new StringBuffer("");
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();
			for (Iterator<Element> iter = root.elementIterator(); iter.hasNext();) {
				Element element = (Element) iter.next();
				if(key.equals(element.getName())){
					sb.append(element.getData());
				}
			}
			return sb.toString();
		} catch (DocumentException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	public static String getElementValue(String key){
		String pathString = XmlUtil.class.getResource("").getPath();
		pathString = pathString.substring(0,pathString.indexOf("classes")+7);
		String sql = XmlUtil.getElementValue(pathString+"/SQL.xml", key);
		return sql;
	}
	

	public static void main(String[] args){
		
		
		
		String pathString = XmlUtil.class.getResource("").getPath();
		pathString = pathString.substring(0,pathString.indexOf("classes")+7);
		String sql = XmlUtil.getElementValue(pathString+"/SQL.xml", "count_1");
		
		sql = sql.replaceAll("\\{condition\\}", "AND DATE_FORMAT(purcheasetime,'%Y-%m-%d')='2010-09-02' AND c.card_type = 2");
		System.out.println(sql);
		
	}
	
	
}
